package com.vf.s.mvc.sys.service;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.vf.core.model.ZtreeNode;
import com.vf.core.render.RenderLayuiBean;
import com.vf.s.common.model.sys.*;
import com.vf.s.mvc.sys.controller.DicController;

public class DicService{
	
	protected final Log LOG = Log.getLog(getClass());

	public List<SysDic> getMenusForUser(String code) {
		return getChildrenAllTree("root",null,code);
	}

	public List<SysDic> getChildrenAllTree(String pId, String userId,String code) {
		List<SysDic> list = getChildrenByPid(pId, userId,code);
		for (SysDic o : list) {
			o.setChildren(getChildrenAllTree(o.getID(),userId,""));
		}
		return list;
	}
	
	/***
	 * 根据id 查询孩子
	 * @param id
	 * @return
	 */
	public List<SysDic> getChildrenByPid(String id,String userid,String code) {
		String sql = "SELECT * FROM "+SysDic.TABLE_NAME+" M WHERE M.PARENTID='" + id + "'   ";
		if(!StrKit.isBlank(code)) {
			sql += " AND CODE LIKE '%"+code+"%' ";
		}
		
		sql = sql + " ORDER BY M.SORT";
		return SysDic.dao.find(sql);
	}

	public RenderLayuiBean listData(DicController menuController) {
		String code=menuController.getPara("code");
		String sqlExceptSelect=" FROM "+SysDic.TABLE_NAME+"  T  WHERE 1=1  ";
		if (!StrKit.isBlank(code)) {
			sqlExceptSelect += " AND T.CODE like '%" + code + "%' ";
		}
		sqlExceptSelect+="  ORDER BY T.SORT ASC";
		List<SysDic> list=SysDic.dao.find("SELECT T.*, (CASE  WHEN (SELECT COUNT(ID) AS COUNT   FROM " +SysDic.TABLE_NAME+" WHERE PARENTID=T.ID)>0 THEN TRUE ELSE  FALSE END ) AS HAVECHILD  "+sqlExceptSelect );
		RenderLayuiBean renderBean=new RenderLayuiBean();
		renderBean.setCode(0);
		renderBean.setMsg("查询成功");
		renderBean.setData(list);
		renderBean.setCount(list.size());
		return renderBean ;
	}

	/***
	 * 菜单转成ZTreeNode
	 * @param olist 数据 open 是否展开所有 ifOnlyLeaf 是否只选叶子
	 * @return
	 */
	public List<ZtreeNode> toZTreeNode(List<SysDic> olist, Boolean open, Boolean ifOnlyLeaf) {
		List<ZtreeNode> list = new ArrayList<ZtreeNode>();
		for (SysDic o : olist) {
			ZtreeNode node = toZTreeNode(o);
			if (o.getChildren() != null && o.getChildren().size() > 0) {// 如果有孩子
				node.setChildren(toZTreeNode(o.getChildren(), open, ifOnlyLeaf));
				if (ifOnlyLeaf) {// 如果只选叶子
					node.setNocheck(true);
				}
				node.setIsParent(true);
			}
			node.setOpen(open);
			list.add(node);
		}
		return list;
	}
	
	public ZtreeNode toZTreeNode(SysDic org) {
		ZtreeNode node = new ZtreeNode();
		node.setId(org.getID());
		node.setName(org.getNAME());
		node.setParentId(org.getPARENTID());
		return node;
	}

	
	public List<SysDicItem> findItemList(String  code) {
		List<SysDicItem> list = SysDicItem.dao.find(
				"SELECT * FROM " + SysDicItem.TABLE_NAME + " WHERE DICID in (select id from "+ SysDic.TABLE_NAME+" where code=? )  order by SORT asc ", code);
		return list;
	}
	
}
